const { Row, Col, Menu, Upload, Icon, Modal, Table, Button, Popconfirm, Input, Cascader, Alert, message, DatePicker, Spin,Select } = antd;
const Option = Select.Option;
const InputGroup = Input.Group;
const imgUrl = 'http://api.moodwo.com/public/index.php/picture/index?id=';
const Banner_uploader = React.createClass({
    getInitialState() {
        return {
            fileList: !this.props.default ? [] : [{
                url: imgUrl + this.props.default
            }]
        };
    },
    uploaderChange(info){
        let fileList = info.fileList;
        // 1. 上传列表数量的限制
        //    只显示最近上传的一个，旧的会被新的顶掉
        fileList = fileList.slice(-1);

        // 2. 读取远程路径并显示链接
        fileList = fileList.map((file) => {
            if (file.response) {
                // 组件会将 file.url 作为链接进行展示
                file.url = imgUrl+file.response.id;
            }
            return file;
        });

        // 3. 按照服务器返回信息筛选成功上传的文件
        fileList = fileList.filter((file) => {
            if (file.response) {
                return parseInt(file.response.status);
            }
            return true;
        });

        this.setState({ fileList });
        if(this.props.selectOver){
            if(this.state.fileList.length!=0){
                if(fileList[0].response)this.props.selectOver(fileList[0].response.id);
            }else{
                this.props.selectOver(0);
            }
        }
    },
    render() {
        const props = {
            name: 'image',
            action: getBaseUrl() + '/admin/file/uploadPicture',
            listType: 'picture-card',
            accept: 'image/*',
            defaultFileList: [],
            fileList: this.state.fileList,
            showUploadList: false,
            onPreview: (file) => {
                this.setState({
                    priviewImage: file.url,
                    priviewVisible: true
                });
            },
            onChange: this.uploaderChange
        };
        const width = this.props.width;
        const height = this.props.height;
        const upload_bg = typeof this.state.fileList[0] !== 'undefined' ? <img src={this.state.fileList[0].url} /> : null;

        return (
            <div className="clearfix" style={{width,height,overflow:'hidden'}}>
                <Upload {...props}>
                    <Icon type="plus" />
                    <div className="ant-upload-text">上传{this.props.name}</div>
                    <div className="upload-bg">{upload_bg}</div>
                </Upload>
            </div>
        );
    }
});
const SearchInput = React.createClass({
    getInitialState() {
        return {
            value: '',
            focus: false
        };
    },
    handleInputChange(e) {
        this.setState({
            value: e.target.value
        });
    },
    handleFocusBlur(e) {
        this.setState({
            focus: e.target === document.activeElement
        });
    },
    handleSearch() {
        if (this.props.onSearch) {
            this.props.onSearch(this.state.value);
        }
    },
    render() {
        const { style, size, placeholder } = this.props;
        const btnCls = classNames({
            'ant-search-btn': true,
            'ant-search-btn-noempty': !!this.state.value.trim()
        });
        const searchCls = classNames({
            'ant-search-input': true,
            'ant-search-input-focus': this.state.focus
        });
        return (
            <div className="ant-search-input-wrapper" style={style}>
                <InputGroup className={searchCls}>
                    <Input placeholder={placeholder} value={this.state.value} onChange={this.handleInputChange}
                           onFocus={this.handleFocusBlur} onBlur={this.handleFocusBlur} onPressEnter={this.handleSearch}
                    />
                    <div className="ant-input-group-wrap">
                        <Button icon="search" className={btnCls} size={size} onClick={this.handleSearch} />
                    </div>
                </InputGroup>
            </div>
        );
    }
});

const Product_Selector = React.createClass({
    getInitialState() {
        return({
            visible: false,
            selectedRowKeys: [],  // 这里配置默认勾选列
            loading: false,
            cateOptions: [],
            originCountryOptions: [],
            originCountry: 0,
            category: [],
            product_list: [],
            product_count: 0,
            nowPage: 1,
            pageSize: 50
        });
    },
    searchCate(){
        //查找指定类目下的商品
        let category = this.state.category;
        let data = {
            size: this.state.pageSize,
            curpage: this.state.nowPage,
            normal_sp: true
        };
        if(this.state.originCountry!=0){
            data.dt_origin_country = this.state.originCountry;
        }
        if(category.length!=0){
            data.cate_id = category.slice(-1)[0];
        }
        let url = getBaseUrl() + '/Admin/AppBanners/queryProduct';

        this.setState({loading: true});

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    this.setState({product_list: data.info.list, product_count:data.info.count, loading: false});
                }else{
                    message.error("数据获取失败");
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("数据获取失败");
                this.setState({loading: false});
            }.bind(this)});
    },
    searchName(value){
        //查找指定名称的商品
        let data = {
            size: this.state.pageSize,
            curpage: this.state.nowPage
        };
        if(this.state.originCountry!=0){
            data.dt_origin_country = this.state.originCountry;
        }
        if(value.trim()!=''){
            data.name = value.trim();
        }
        let url = getBaseUrl() + '/Admin/AppBanners/queryProduct';

        this.setState({loading: true});

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    this.setState({product_list: data.info.list, product_count:data.info.count, loading: false});
                }else{
                    message.error("数据获取失败");
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("数据获取失败");
                this.setState({loading: false});
            }.bind(this)});
    },
    showModal() {
        this.setState({
            visible: true,
            selectedRowKeys: []
        });
        let url = getBaseUrl() + '/Admin/AppBanners/queryCategory';
        _get(url,{data_back: function(data){
            if(data){
                this.setState({cateOptions: data});
            }
        }.bind(this)});

        let url2 = getBaseUrl() + '/Admin/AppBanners/queryOriginCountry';
        _get(url2,{data_back: function(data){
            if(data){
                this.setState({originCountryOptions: data});
            }
        }.bind(this)});

        this.searchCate();
    },
    handleOk() {
        let selectedRowKeys = this.state.selectedRowKeys;
        if(this.props.onSelectOver){
            this.props.onSelectOver(selectedRowKeys);
        }
        this.setState({
            visible: false
        });
    },
    handleCancel(e) {
        this.setState({
            visible: false
        });
    },
    onTableSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys });
    },
    onCateChange(value){
        //类目选择器值改变
        this.setState({category: value});

    },
    originCountryChange(value){
        //产销国选择器值改变
        let s = value!='undefined' ? value : 0;

        this.setState({originCountry:s});
    },
    render(){
        const columns = [
            { title: 'ID', dataIndex: 'id', key: 'id', width:80},
            { title: '商品图片', dataIndex: 'pic', key: 'pic', width:150, render:(img)=> <img style={{maxWidth:80,maxHeight:80}} src={img} />},
            { title: '商品名称', dataIndex: 'name', key: 'name', render: (name)=> <a href="javascript:void(0);">{name}</a> }
        ];

        const data = this.state.product_list.map(function(val){
            return({
                key: val.id,
                id: val.id,
                pic: val.img_id,
                name: val.name
            });
        });

        const { loading, selectedRowKeys } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onTableSelectChange,
            type:this.props.type?this.props.type:"checkbox"
        };
        const pagination = {
            total: this.state.product_count,
            showSizeChanger: true,
            onChange:function(current) {
                this.setState({nowPage: current});
                this.searchCate();
            }.bind(this),
            pageSize: this.state.pageSize
        };
        
        const originCountryOptions = this.state.originCountryOptions.map(function(val){
            return <Option value={val.code}>{val.name}</Option>
        });

        return(
            <div style={{display: 'inline-block',marginTop:5}}>
                <Button type="primary" style={{marginRight:10}} onClick={this.showModal}>添加商品</Button>
                <Modal title="给分组添加商品" visible={this.state.visible}
                       onOk={this.handleOk} onCancel={this.handleCancel}
                       width="1000"
                       style={{ top: 50 }}
                >
                    <Row type="flex" align="middle" gutter="16" className="row-group">
                        <Col><h3 style={{marginLeft:14}}>产销国:</h3></Col>
                        <Col>
                            <Select allowClear placeholder="请选择产销国" showSearch
                                    optionFilterProp="children"
                                    onChange={this.originCountryChange}
                                    notFoundContent="无法找到" style={{ width: 160}}>
                                {originCountryOptions}
                            </Select>
                        </Col>
                    </Row>
                    <Row type="flex" align="middle" gutter={16} className="row-group">
                        <Col><h3>搜索商品:</h3></Col>
                        <Col>
                            <SearchInput placeholder="请输入商品名称"
                                         onSearch={this.searchName} style={{ width: 300 }}
                            />
                        </Col>
                    </Row>
                    <Row type="flex" align="middle" gutter={16}  className="row-group">
                        <Col><h3>选择类目:</h3></Col>
                        <Col><Cascader options={this.state.cateOptions} onChange={this.onCateChange} placeholder="请选择类目" style={{width:300}} /></Col>
                        <Col><Button type="default" loading={loading} onClick={this.searchCate}>确定</Button></Col>
                    </Row>
                    <Row>
                        <Alert message="从列表中勾选需要添加的商品，点击右下角的确认按钮完成添加~" type="info" />
                    </Row>
                    <Row>
                        <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={pagination} scroll={{ y: 400 }} loading={loading} type={this.props.type?this.props.type:null} />
                    </Row>
                </Modal>
            </div>
        );
    }
});

const Sku_selector = React.createClass({
    getDefaultProps(){
        return({
            pid: 0,
            default_sku: []
        });
    },
    getInitialState(){
        return({
            visible: false,
            selectedRowKeys: [],  // 这里配置默认勾选列
            loading: false,
            cateOptions : [],
            sku_list: []
        });
    },
    onSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys });
    },
    handleOk() {
        //组合返回数据
        let selectedRowKeys = this.state.selectedRowKeys;
        let sku = this.state.sku_list.filter(function(val){
            for(let i=0; i< selectedRowKeys.length; i++){
                if(selectedRowKeys[i]==val.key) return true;
            }
            return false;
        });

        if(this.props.onSelectOver){
            this.props.onSelectOver(this.props.pid,sku);
        }
        this.setState({
            visible: false
        });
    },
    handleCancel(e) {
        this.setState({
            visible: false
        });
    },
    show(){
        this.setState({
            visible: true
        });
        let url = getBaseUrl() + '/Admin/AppBanners/querySku';

        let data = {
            pid: this.props.pid
        };

        this.setState({loading: true});

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    let selectedRowKeys = [];
                    let sku_list = data.info.map(function(val){
                        let ret = {
                            key: val.id,
                            name: val.product_name,
                            sku: val.sku_desc,
                            sku_id: val.id,
                            start_time:0,
                            end_time:0,
                            price:0,
                            display_order:0
                        };
                        this.props.default_sku.forEach(function(v2){
                            if(v2.sku_id==val.id){
                                ret.start_time = v2.start_time;
                                ret.end_time = v2.end_time;
                                ret.price = v2.price;
                                ret.display_order = v2.display_order;
                                selectedRowKeys.push(val.id);
                            }
                        });
                        return ret;
                    }.bind(this));
                    this.setState({selectedRowKeys});

                    this.setState({sku_list: sku_list, loading: false});
                }else{
                    message.error(data.info);
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("数据获取失败");
                this.setState({loading: false});
            }.bind(this)});
    },
    onDateChange(id,date,type){
        let time = Date.parse(date)/1000;
        let sku_list = this.state.sku_list;
        sku_list.forEach(function(val,index){
            if(val.key==id)sku_list[index][type]= time;
        });
        this.setState({sku_list});

    },
    onInputChange(id,value,type){
        let sku_list = this.state.sku_list;
        sku_list.forEach(function(val,index){
            if(val.key==id)sku_list[index][type] = value;
        });
        this.setState({sku_list});
    },

    render(){
        const { loading, selectedRowKeys } = this.state;
        const default_time = this.props.default_time?this.props.default_time:null;
        const columns = [
            { title: '商品名称', dataIndex: 'name', key: 'id', width:150},
            { title: '商品规格', dataIndex: 'sku', key: 'sku', width:150},
            { title: '开始时间', dataIndex: 'start_time', key: 'start_time', width:200,
                render:(text,record)=>
                    <DatePicker defaultValue={default_time?new Date(default_time.start_time*1000):
                    (text!=0 ? new Date(text*1000) : null)}
                                showTime format="yyyy-MM-dd HH:mm:ss"
                                onChange={(date,dateString)=>this.onDateChange(record.key,date,'start_time')}
                                disabled={default_time?true:null}
                    />
            },
            { title: '结束时间', dataIndex: 'end_time', key: 'end_time', width:200,
                render:(text,record)=>
                    <DatePicker defaultValue={default_time?new Date(default_time.end_time*1000):
                    (text!=0 ? new Date(text*1000) : null)}
                                showTime format="yyyy-MM-dd HH:mm:ss"
                                onChange={(date,dateString)=>this.onDateChange(record.key,date,'end_time')}
                                disabled={default_time?true:null}
                    />
            },
            { title: '活动价', dataIndex: 'price', key: 'price', width:100,
                render:(text,record)=>
                    <Input type="text" defaultValue={text}
                           onChange={(event)=>this.onInputChange(record.key,event.target.value,'price')}
                    />
            },
            { title: '显示顺序', dataIndex: 'display_order', key: 'display_order', width:80,
                render:(text,record)=>
                    <Input type="text" defaultValue={text}
                           onChange={(event)=>this.onInputChange(record.key,event.target.value,'display_order')}
                    />
            }
        ];
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        };

        const data = this.state.sku_list;

        const modal = !this.state.visible ? null : [
            <Modal
                title="选择商品规格设置分组" visible={this.state.visible}
                onOk={this.handleOk} onCancel={this.handleCancel}
                width="1000"
                style={{ top: 50 }}
            >
                <Row>
                    <Alert message="从列表中勾选需要添加到分组的规格，设置完属性后点击右下角确定完成~" type="info" />
                </Row>
                <Row>
                    <Table rowSelection={rowSelection} columns={columns} dataSource={data} scroll={{ y: 500 }} loading={loading} />
                </Row>
            </Modal>
        ];
        return(
            <div style={{display:'inline-block',marginRight:5}}>
                <a href="javascript:void(0);" onClick={this.show}>选择规格</a>
                {modal}
            </div>
        );
    }
});

const Group_box =React.createClass({
    getDefaultProps(){
        return({
            product_ids:[],
            product_sku:[],
            title:'分组商品列表'
        });
    },
    getInitialState(){
        return {
            selectedRowKeys: [],  // 这里配置默认勾选列
            loading: false,
            product_ids: this.props.product_ids,
            product_sku: this.props.product_sku,
            product_list: [],
            product_count: 0,
            nowPage: 1,
            pageSize: 50
        };
    },
    componentDidMount(){
        this.searchProduct();
    },
    onSelectChange(selectedRowKeys) {
        this.setState({ selectedRowKeys });
    },
    selectDelete(ids){
        let product_ids = this.state.product_ids;
        let product_sku = this.state.product_sku;
        ids.forEach(function(val){
            delete product_sku[val];
        });
        product_ids = product_ids.filter(function(val){
            for(let i=0; i<ids.length; i++){
                if(val==ids[i]){
                    return false;
                }
            }
            return true;
        });
        this.searchProduct(product_ids);
        this.setState({
            product_sku
        });
        if(this.props.onSelectProductOver){
            this.props.onSelectProductOver(product_ids,product_sku);
        }
    },
    searchProduct(ids=false){
        let product_ids = ids ? ids : this.state.product_ids;
        let url = getBaseUrl() + '/Admin/AppBanners/queryProduct';
        if(product_ids.length==0) product_ids = [0];
        let data = {
            ids: product_ids,
            size: this.state.pageSize,
            curpage: this.state.nowPage
        };
        this.setState({loading: true, product_ids: product_ids});

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    this.setState({product_list: data.info.list, product_count:data.info.count, loading: false});
                }else{
                    message.error("数据获取失败");
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("数据获取失败");
                this.setState({loading: false});
            }.bind(this)});
    },
    onSelectProductOver(selectedRowKeys){
        let product_ids = this.state.product_ids;
        product_ids = product_ids.concat(selectedRowKeys);
        product_ids = unique(product_ids);
        this.searchProduct(product_ids);
        if(this.props.onSelectProductOver){
            let product_sku = this.state.product_sku;
            this.props.onSelectProductOver(product_ids,product_sku);
        }
    },
    onSelectSkuOver(pid,sku){
        let product_sku = this.state.product_sku;
        product_sku[pid] = sku;
        this.setState({product_sku});
        if(this.props.onSelectProductOver){
            let product_sku = this.state.product_sku;
            let product_ids = this.state.product_ids;
            this.props.onSelectProductOver(product_ids,product_sku);
        }
    },
    render(){
        const { loading, selectedRowKeys } = this.state;
        const columns = [
            { title: 'ID', dataIndex: 'id', key: 'id', width:80},
            { title: '商品图片', dataIndex: 'pic', key: 'pic', width:150, render:(img)=> <img style={{maxWidth:80,maxHeight:80}} src={img} />},
            { title: '商品名称', dataIndex: 'name', key: 'name', width:250, render: (name)=> <a href="javascript:void(0);">{name}</a> },
            { title: '操作', dataIndex: '', key: 'x', width:150,
                render: (rocord)=>
                    <div>
                        <Sku_selector pid={rocord.id} onSelectOver={this.onSelectSkuOver}
                                      default_sku={rocord.default_sku}
                                      default_time={this.props.default_time}/>
                        <Popconfirm title="确定要从分组中删除这个商品吗？" onConfirm={()=>this.selectDelete([rocord.id])}>
                            <a href="javascript:void(0);">删除</a>
                        </Popconfirm>
                    </div>
            }
        ];

        const data = this.state.product_list.map(function(val){
            return({
                key: val.id,
                id: val.id,
                pic: val.img_id,
                name: val.name,
                default_sku: this.state.product_sku[val.id] ? this.state.product_sku[val.id] : []
            });
        }.bind(this));

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange
        };
        const pagination = {
            total: this.state.product_count,
            showSizeChanger: true,
            onChange:function(current) {
                this.setState({nowPage: current});
                this.searchProduct();
            }.bind(this),
            pageSize: this.state.pageSize
        };

        return(
            <div>
                <h3>{this.props.title}</h3>
                <div style={{marginBottom: 20}}>
                    <Product_Selector onSelectOver={this.onSelectProductOver} />
                    <Popconfirm title="确定要从分组中删除这些选中的商品吗？" onConfirm={()=>this.selectDelete(selectedRowKeys)}>
                        <Button type="primary">选中项删除</Button>
                    </Popconfirm>
                </div>
                <Table rowSelection={rowSelection} columns={columns} dataSource={data} pagination={pagination} scroll={{ y: 500 }} loading={loading} />
            </div>
        );
    }
});

//首页商品、分组商品选择
const Products_inline = React.createClass({
    getDefaultProps(){
        return({
            product_ids:[],
            title:'商品',
            max: false
        });
    },
    getInitialState(){
        return({
            product_list: [],
            product_ids: this.props.product_ids,
            loading: false
        });
    },
    componentDidMount(){
        this.searchProduct();
    },
    searchProduct(ids=false){
        let product_ids = ids ? ids : this.state.product_ids;
        let url = getBaseUrl() + '/Admin/AppBanners/queryProduct';
        if(this.props.max){
            if(product_ids.length>parseInt(this.props.max)){
                product_ids = product_ids.slice(0,this.props.max);
            }
        }

        let data = {
            ids: product_ids,
            size: 10,
            curpage: 1,
        };
        if(product_ids.length==0) data.ids = [0];
        this.setState({loading: true, product_ids: product_ids});

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    this.setState({product_list: data.info.list, product_count:data.info.count, loading: false});
                }else{
                    message.error("数据获取失败");
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("数据获取失败");
                this.setState({loading: false});
            }.bind(this)});
    },
    onSelectProductOver(selectedRowKeys){
        let product_ids = this.state.product_ids;
        product_ids = product_ids.concat(selectedRowKeys);
        product_ids = unique(product_ids);
        this.searchProduct(product_ids);
        if(this.props.onSelectProductOver){
            this.props.onSelectProductOver(product_ids);
        }
    },
    delete(id){
        let product_ids = this.state.product_ids.filter(function(val){
            return val!=id;
        });
        if(this.props.onSelectProductOver){
            this.props.onSelectProductOver(product_ids);
        }
        this.searchProduct(product_ids);

    },
    render(){
        const list = this.state.product_list.map(function(val){
            return <li key={val.id}>{val.name}<a href="javascript:void(0);" onClick={()=>this.delete(val.id)}>删除</a></li>
        }.bind(this));
        let show_selector = true;
        if(this.props.max && this.state.product_ids.length>= parseInt(this.props.max)) show_selector=false;

        return(
            <div>
                <h3>{this.props.title}</h3>
                {show_selector ? <Product_Selector onSelectOver={this.onSelectProductOver} type="radio" /> : null}
                <ul className="show-sp">
                    <Spin spinning={this.state.loading}>
                        {list}
                    </Spin>
                </ul>
            </div>
        );
    }
});

//分组活动时间
const Group_main_time = React.createClass({
    getInitialState(){
        return({
            main_date:{
                start_time:this.props.startTime,
                end_time:this.props.endTime
            }
        });
    },
    onDateChange(date,type){
        let main_date = this.state.main_date;
        if(type=='start_time'){
            main_date.start_time = Date.parse(date)/1000;
            this.setState({main_date});
        }
        if(type=='end_time'){
            main_date.end_time = Date.parse(date)/1000;
            this.setState({main_date});
        }
        
        if(this.props.onDateChange){
            this.props.onDateChange(main_date);
        }
    },
    render(){
        const startTime = this.props.startTime;
        const endTime = this.props.endTime;
        return(
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{this.props.title}</h3>
                <div style={{paddingLeft:10}}>
                    <div style={{marginTop:5}}>
                        <span style={{marginRight:5}}>活动开始时间:</span>
                        <DatePicker defaultValue={startTime!=0 ? new Date(startTime*1000) : null} showTime format="yyyy-MM-dd HH:mm:ss"
                                    onChange={(date,dateString)=>this.onDateChange(date,'start_time')}
                        />
                    </div>
                    <div style={{marginTop:5}}>
                        <span style={{marginRight:5}}>活动结束时间:</span>
                        <DatePicker defaultValue={endTime!=0 ? new Date(endTime*1000) : null} showTime format="yyyy-MM-dd HH:mm:ss"
                                    onChange={(date,dateString)=>this.onDateChange(date,'end_time')}
                        />
                    </div>
                </div>
            </div>
        );
    }
});

//分组主图
const Group_main_banner = React.createClass({
    bannerSelectOver(id){
        if(this.props.bannerSelectOver){
            this.props.bannerSelectOver(id);
        }
    },
    render(){
        return(
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{this.props.title}</h3>
                <Banner_uploader name={'分组主图'} width="100%" height="360" default={this.props.default?this.props.default:null}
                                 selectOver={this.bannerSelectOver}
                />
            </div>
        );
    }
});


const Block_setor = React.createClass({
    getInitialState(){
        return({
            now_banner: 0,
            block: this.props.block ? this.props.block : false,
            loading: false
        });
    },
    setNowBanner(index){
        this.setState({now_banner: -1, loading: true});
        setTimeout(()=>this.setState({now_banner:index, loading:false}),200);
    },
    product_home_select_over(product_ids){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].product_home.product_ids = product_ids;
            }else{
                block.banners.product_home.product_ids = product_ids;
            }
            this.setState({block});
        }
    },
    product_group_select_over(product_ids){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].product_group.product_ids = product_ids;
            }else{
                block.banners.product_group.product_ids = product_ids;
            }
            this.setState({block});
        }
    },
    group_product_list_select_over(product_ids,sku){
        if(this.state.block){
            let { now_banner, block } = this.state;
            let group_product_list = {
                p_ids: product_ids,
                sku: sku
            };
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].group_product_list = group_product_list;
            }else{
                block.banners.group_product_list = group_product_list;
            }
            this.setState({block});
        }
    },
    bannerSelectOver(key,id){
        if(this.state.block){
            let { block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners = block.banners.map(function(val){
                    if(val.key==key){
                        val.id=id;
                    }
                    return val;
                });
            }else{
                block.banners.id = id;
            }
            this.setState({block});
        }
    },
    onGroupMainBannerChange(id){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].group_main_banner = {id};
            }else{
                block.banners.group_main_banner = {id};
            }
            this.setState({block});
        }
    },
    onGroupMainTimeChange(date){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].group_main_time = date;
            }else{
                block.banners.group_main_time = date;
            }
            this.setState({block});
        }
    },
    onChangeName(e){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].name = e.target.value;
            }else{
                block.banners.name = e.target.value;
            }
            this.setState({block});
        }
    },
    onChangeTitle(e){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].title = e.target.value;
            }else{
                block.banners.title = e.target.value;
            }
            this.setState({block});
        }
    },
    onChangeDesc(e){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].desc = e.target.value;
            }else{
                block.banners.desc = e.target.value;
            }
            this.setState({block});
        }
    },
    onChangeDiscount(e){
        if(this.state.block){
            let { now_banner, block } = this.state;
            if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                block.banners[now_banner].discount = e.target.value;
            }else{
                block.banners.discount = e.target.value;
            }
            this.setState({block});
        }
    },
    blockSave(){
        this.setState({loading: true});
        let block = this.state.block;
        if(!block.block_id){
            this.setState({loading: false});
            message.error('数据异常,保存失败');
            console.log('block',block);
            return;
        }
        let newPageInfo = pageInfo;
        for(let i=0; i<newPageInfo.page_data.length; i++){
            if(newPageInfo.page_data[i].block_id==block.block_id){
                newPageInfo.page_data[i] = block;
                break;
            }
        }

        //保存
        let url = getBaseUrl() + '/Admin/AppBanners/savePage';
        let data = {
            page_info: JSON.stringify(newPageInfo)
        };

        _post(url,jQuery.param(data),{
            data_back: function(data){
                if(data.status){
                    message.success("保存成功");
                    //让设计器重新加载数据
                    if(this.props.saveBack){
                        this.props.saveBack();
                    }
                    this.setState({loading: false});
                }else{
                    message.error("保存失败");
                    this.setState({loading: false});
                }
            }.bind(this),
            error: function(){
                message.error("保存失败");
                this.setState({loading: false});
            }.bind(this)});

    },
    render(){
        const block = this.props.block;
        const banners = block.banners ? block.banners.map(function(val,index){
            return(
                <li style={{textAlign: 'center'}} style={{width:val.width}}>
                    <Banner_uploader name={val.name} width={val.width} height={val.height} default={val.id!=0 ? val.id : null}
                                     selectOver={(id)=>this.bannerSelectOver(val.key,id)}
                    />
                    <Button type="default" size="small" style={{marginTop: 10}} onClick={()=>this.setNowBanner(index)}>设置此分组</Button>
                </li>
            )
        }.bind(this)) : null;



        let now_banner = {};
        if(this.state.now_banner != -1){
            if(this.props.block){
                if(Object.prototype.toString.call(block.banners)=='[object Array]'){
                    now_banner = block.banners[this.state.now_banner];
                }else{
                    now_banner = block.banners;
                }
            }
        }

        //分组名称
        const group_name = typeof now_banner.name !='undefined' ? [
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{`分组名称(APP标题)[${now_banner.name}]key=>${now_banner.key}`}</h3>
                <Input style={{width:300}} placeholder="分组名称" defaultValue={now_banner.name} onChange={this.onChangeName} />
            </div>
        ] : null;

        //分组标题
        const group_title = typeof now_banner.title !='undefined' ? [
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{`分组标题[${now_banner.name}]key=>${now_banner.key}`}</h3>
                <Input style={{width:300}} placeholder="分组标题" defaultValue={now_banner.title} onChange={this.onChangeTitle} />
            </div>
        ] : null;
        //分组desc
        const group_desc = typeof now_banner.desc !='undefined' ? [
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{`分组desc[${now_banner.name}]key=>${now_banner.key}`}</h3>
                <Input type="textarea" placeholder="分组详细文字" defaultValue={now_banner.desc} autosize style={{width:300,minHeight:100}} onChange={this.onChangeDesc} />
            </div>
        ] : null;
        //分组折扣(只显示)
        const group_discount = typeof now_banner.discount !='undefined' ? [
            <div style={{marginBottom:10}}>
                <h3 style={{marginBottom:5}}>{`分组折扣(只显示)[${now_banner.name}]key=>${now_banner.key}`}</h3>
                <Input style={{width:40,textAlign:'center'}} placeholder="分组折扣" defaultValue={now_banner.discount} onChange={this.onChangeDiscount} /><span style={{marginLeft:5}}>折</span>
            </div>
        ] : null;

        // 分组主图
        const group_main_banner = now_banner.group_main_banner ? <Group_main_banner title={`分组主图[${now_banner.name}]key=>${now_banner.key}`}
                                                                                    default={now_banner.group_main_banner.id}
                                                                                    bannerSelectOver={this.onGroupMainBannerChange}/> : null;

        // 分组活动时间 子级SKU时间全为此时间
        const group_main_time = now_banner.group_main_time ? <Group_main_time title={`分组活动时间[${now_banner.name}]key=>${now_banner.key}`}
                                                                              startTime={now_banner.group_main_time.start_time}
                                                                              endTime={now_banner.group_main_time.end_time}
                                                                              onDateChange={this.onGroupMainTimeChange}/> : null;

        const product_home = now_banner.product_home ? <Products_inline title={`首页商品[${now_banner.name}]key=>${now_banner.key}`}
                                                                        product_ids={now_banner.product_home.product_ids} max={now_banner.product_home.max}
                                                                        onSelectProductOver={this.product_home_select_over} /> : null;

        const product_group = now_banner.product_group ? <Products_inline title={`分组首页商品[${now_banner.name}]key=>${now_banner.key}`}
                                                                          product_ids={now_banner.product_group.product_ids} max={now_banner.product_group.max}
                                                                          onSelectProductOver={this.product_group_select_over}  /> : null;

        const group_product_list = now_banner.group_product_list ?<Group_box title={`分组商品列表[${now_banner.name}]key=>${now_banner.key}`}
                                                                             product_ids={now_banner.group_product_list.p_ids}
                                                                             product_sku={now_banner.group_product_list.sku}
                                                                             default_time={group_main_time?now_banner.group_main_time:null} //默认时间，则分组SKU时间无法选择
                                                                             onSelectProductOver={this.group_product_list_select_over} />: null;

        return(
            <div className="block-set">
                <Spin spinning={this.state.loading}>
                    <a style={{position:'absolute',right:10,top:10}} onClick={this.props.hide} href="javascript:void(0);"><Icon type="cross" /></a>
                    <h3>上传图片</h3>
                    <ul className="banners">
                        {banners}
                    </ul>
                    {group_name}
                    {group_title}
                    {group_desc}
                    {group_discount}
                    {group_main_banner}
                    {group_main_time}
                    {product_home}
                    {product_group}
                    {group_product_list}
                    <div className="btn-group">
                        <Button type="default" onClick={this.props.hide} style={{marginRight:5}}>取消</Button>
                        <Button type="primary" onClick={this.blockSave}>保存</Button>
                    </div>
                </Spin>
            </div>
        );
    }
});